﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Chest : LootTable, IInteractable 
{
    [SerializeField]
    private SpriteRenderer chestRenderer;
    [SerializeField]
    private Sprite openChest, closedChest;
    private bool isOpen = false;
    [SerializeField]
    private ChestScript chestWindow;
    [SerializeField]
    private CanvasGroup chestCanvas;
    [SerializeField]
    private bagScript bagWindow;
    [SerializeField]
    private bool isTreasure = false;
    public List<Drop> MyDrop { get; set; }
    //[SerializeField]
    //private int slotCount=15;
    private List<Item> items=new List<Item>();

    public List<Item> MyItems { get => items; set => items = value; }
    public bagScript MyBag { get => bagWindow; set => bagWindow = value; }

    private void Awake()
    {
        items = new List<Item>();
    }
    public void Interact()
    {
        if (isOpen)
        {
            StopInteract();
        }
        else
        {
            
            if (isTreasure)
            {
                ShowLoot();

            }
            ReturnItems();
            isOpen = true;
            chestRenderer.sprite = openChest;
            chestCanvas.alpha = 1;
            chestCanvas.blocksRaycasts = true;
            
        }
        
    }

    public void StopInteract()
    {
        StoreItems();
        isOpen = false;
        chestRenderer.sprite = closedChest;
        chestCanvas.alpha = 0;
        chestCanvas.blocksRaycasts = false;
        MyBag.Clear();
        Player.MyInstance.MyInteractables.Clear();
        Player.MyInstance.MyInteractable = null;

    }

    protected override void RollLoot()
    {
        foreach (Loot item in loot)
        {
            int luck = Random.Range(0, 100);
            if (luck <= item.MyDropChanse)
            {
                MyBag.AddItem(item.MyItem);
            }
        }
        gotRolled = true;
    }

    public override List<Drop> ShowLoot()
    {
        if (!gotRolled)
        {
            MyDrop = new List<Drop>();
            RollLoot();
        }
        return MyDrop;
    }
    public void StoreItems()
    {
        MyItems = MyBag.GetItems();
       
    }
    private void ReturnItems()
    {

        if (MyItems != null)
        {
          
            foreach (Item i in MyItems)
            {
                i.Slot.AddItem(i);
            }
        }
    }
}
